<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入所属商家名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="cretTime">
        <el-date-picker clearable
          v-model="queryParams.cretTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择菜品创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wx-applet:orderInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wx-applet:orderInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx-applet:orderInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wx-applet:orderInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="所属商家id" align="center" prop="storeId" />-->
      <el-table-column label="所属商家名称" align="center" prop="storeName" />
<!--      <el-table-column label="菜品id" align="center" prop="orderId" />-->
      <el-table-column label="菜品名称" align="center" prop="orderName" />
<!--      <el-table-column label="图片名称" align="center" prop="picName" />
      <el-table-column label="图片存储路径" align="center" prop="picPath" />
      <el-table-column label="图片类型" align="center" prop="picType" />
      <el-table-column label="菜品类别" align="center" prop="orderType" />-->
      <el-table-column label="菜品价格（元）" align="center" prop="orderPrice" />
      <el-table-column label="是否上架" align="center" prop="isShow" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_show" :value="scope.row.isShow"/>
        </template>
      </el-table-column>
      <el-table-column label="菜品创建时间" align="center" prop="cretTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cretTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="备注" align="center" prop="remarks" />-->
      <el-table-column label="最后更新时间" align="center" prop="updtTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updtTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="菜品详情" align="center" prop="orderContent"  width="300"/>-->
      <el-table-column label="对应菜品排序" align="center" prop="orderBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wx-applet:orderInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx-applet:orderInfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="所属商家id" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入所属商家id" />
        </el-form-item>-->
        <el-form-item label="商家名称" prop="storeName">
<!--          <el-input v-model="form.storeName" placeholder="请输入所属商家名称" />-->
          <div id="app">
           <!-- 输入框，绑定输入框的值是变量input_value的值,然后对输入框做了事件绑定keyup，在用户输入的时候会触发 -->
            <input type="text" placeholder="请输入商家名称进行查询" v-model="input_value" @keyup="throttle" ref="input" style="height: 36px;line-height: 36px;border: 1px solid #DCDFE6;border-radius: 4px;color:#606266;width: 100%;padding: 0 15px;font-size: inherit;"/>
            <ul v-show="state">
              <li v-for="(item,index) in list" :key="index" style="list-style:none;margin-left: -40px;color: #606266;font-size: inherit;" >
                <span @click="is_check(item.id,item.nickName)" style="cursor:pointer;">{{item.nickName}}</span>
              </li>
            </ul>
          </div>
        </el-form-item>
<!--        <el-form-item label="菜品id" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入菜品id" />
        </el-form-item>-->
        <el-form-item label="菜品名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderBy">
          <el-input v-model="form.orderBy" placeholder="请输入排序" />
        </el-form-item>
<!--        <el-form-item label="图片名称" prop="picName">
          <el-input v-model="form.picName" placeholder="请输入图片名称" />
        </el-form-item>
        <el-form-item label="图片存储路径" prop="picPath">
          <el-input v-model="form.picPath" placeholder="请输入图片存储路径" />
        </el-form-item>-->
        <el-form-item label="菜品价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入菜品价格" />
        </el-form-item>
        <el-form-item label="菜品详情">
          <editor v-model="form.orderContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="菜品上传">
          <div class="file">
            <input type="file" class="updata" accept="image/*" @change="change($event)" ref="updata">
            <img :src="this.baseImg" alt="" class="img">
          </div>
        </el-form-item>
        <el-form-item label="是否上架">
          <el-radio-group v-model="form.isShow">
            <el-radio
              v-for="dict in dict.type.is_show"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="创建时间" prop="cretTime">
          <el-date-picker clearable
                          v-model="form.cretTime"
                          type="date"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择菜品创建时间">
          </el-date-picker>
        </el-form-item>-->
<!--          <el-input v-model="form.orderType" type="textarea" placeholder="请输入内容" />-->
        <el-form-item label="菜品类别">
          <div v-for="(i, j) in list_order" :key="j" class="add-box" style="width:100%;float: left;">
            <div class="f jc-b" style="float: left; width:42%;margin-top: 5px;">规格:&nbsp;&nbsp;<el-input type="text" style="width: 120px;" v-model="postRequire[j]" placeholder="请输入规格"/></div>
            <div class="f jc-b" style="float: left; width:42%;margin-top: 5px;">价格:&nbsp;&nbsp;<el-input type="text" style="width: 120px;" v-model="comment[j]" placeholder="请输入价格"/></div>
            <div style="float: left; width:10%;margin-top: 5px;"><el-button style="background-color:red;color: #FFFFFF" @click="rev(j)">删除</el-button></div>
          </div>
          <el-button style="background-color:limegreen;color: #FFFFFF;margin-top: 10px;" @click="AddPeople">添加</el-button>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="更新时间" prop="updtTime">
          <el-date-picker clearable
                          v-model="form.updtTime"
                          type="date"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo,upload_img,getStore } from "@/api/system/order";
import {deptTreeSelect} from "@/api/system/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Info",
  components: {Treeselect},
  dicts: ['is_show'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 默认的图片
      baseImg: '',
      // 显示搜索条件
      showSearch: true,
      // 投诉类别
      isShow_data:[{'id':'0',name:'否'},{'id':'1',name:'是'}],
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      infoList: [],
      //商家名称list
      storeList:[],
      //商家id
      s_id:null,
      //商家名称
      s_name:null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //追加菜品类别
      list_order: [],
      postRequire: [], //岗位要求
      comment: [], //评论
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        storeName: null,
        orderId: null,
        orderName: null,
        orderBy: null,
        picName: null,
        picPath: null,
        picType: null,
        orderType: null,
        orderPrice: null,
        orderContent: null,
        cretTime: null,
        remarks: null,
        updtTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      input_value:"",
      state:false,
      statu:true,
      list:[],
      order_type:""
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getStoreList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否上架
    isShow(row, column){
      if (row.isShow == 0) {
        return '否';
      } else if (row.isShow == 1) {
        return '是';
      }
    },
    /**  菜品附件上传 */
    change(e) {
      console.log(e.target.files[0].name);
      // 判断是不是规定格式
      // let name  =  e.target.files[0].name
      let formData = new window.FormData();
      // 获取到第一张图片
      let file = e.target.files[0]
      formData.append('file',file);
      console.info(file);
      // 创建文件读取对象
      var reader = new FileReader()
      var that = this
      //  将文件读取为DataURL
      reader.readAsDataURL(file)
      // 读取成功调用方法
      reader.onload = e => {
        console.log('读取成功');
        // // e.target.result 获取 读取成功后的  文件DataURL
        // that.imageUrl = e.target.result
        // 如果要将图片上传服务器，就在这里调用后台方法
        upload_img(formData).then(response => {
          that.baseImg =response.imgUrl;
        });
      }
    },
    deptall(val){
      //获取选中商家名称
      this.deptName=val.label;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeId: null,
        storeName: null,
        orderId: null,
        orderName: null,
        orderBy: null,
        picName: null,
        picPath: null,
        picType: null,
        orderType: null,
        orderPrice: null,
        orderContent: null,
        cretTime: null,
        remarks: null,
        updtTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      //给搜索文本框赋值为空
      this.input_value='';
      // 获取默认显示的图片
      this.baseImg = require('./pic/sc_bj.png');
      this.reset();
      this.getDeptTree();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getDeptTree();
      //修改未刷新页面时，将值赋空值
      this.list_order=[];
      this.postRequire=[];
      this.comment=[];
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        //修改时给菜品类型赋值
        if(this.form.orderType!=null&&this.form.orderType!=''&&this.form.orderType!='undefined'){
          let o_t_v = [];
          for (let index = 0; index < this.form.orderType.split(',').length; index++) {
            let o_type_value = this.form.orderType.split(',')[index];
            this.list_order.push({
              postRequire: o_type_value.split('-')[0],
              comment: o_type_value.split('-')[1],
            });
            this.postRequire.push(o_type_value.split('-')[0]);
            this.comment.push(o_type_value.split('-')[1]);
          }
        }
        //给搜索文本框赋值
        this.input_value=this.form.storeName;
        //回显图片
        if(this.form.picPath!=null&&this.form.picPath!=''&&this.form.picPath!='undefined'){
          this.baseImg=this.form.picPath;
        }else{
          // 获取默认显示的图片
          this.baseImg = require('./pic/sc_bj.png')
        }
        this.open = true;
        this.title = "修改【菜品信息】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      //给商家名称赋值为下拉树选中的值
      if(this.input_value!=this.form.storeName){
        this.$set(this.form, "storeId", this.s_id);
        this.$set(this.form, "storeName", this.s_name);
      }

      //追加菜品规格类型
      if(this.postRequire.length>0&&this.postRequire[0]!=null&&this.postRequire[0]!=''&&this.postRequire[0]!='undefined') {
        this.order_type="";
        //追加规格类型
        for (let index = 0; index < this.postRequire.length; index++) {
          this.order_type += this.postRequire[index] + '-' + this.comment[index] + ',';
        }
        this.$set(this.form, "orderType", this.order_type.substring(0,this.order_type.length-1));
      }
      //将图片地址存入数据库，为空证明用户没有上传菜品图片
      if(this.baseImg!=null&&this.baseImg!=''&&this.baseImg!='undefined'){
        //图片路径
        this.$set(this.form, "picPath", this.baseImg);
        //图片类型
        this.$set(this.form, "picType", this.baseImg.split(".")[this.baseImg.split(".").length-1]);
        //图片名称
        let p_name=this.baseImg.split("/")[this.baseImg.split("/").length-1]
        this.$set(this.form, "picName", p_name.substring(0,p_name.length-4));
      }
      //写入数据到数据库
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('test1/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    throttle(){
      //定义的新数组存放筛选之后的数据
      this.list=[];
      //拿到当前input输入框输入的值
      this.input_value=this.$refs.input.value;
      //判断展示ul列表，如果输入了就展示没输入就不展示
      if(this.input_value.length>0){
        this.state=true;
      }else{
        this.state=false;
      }
      //循环模拟数据的数组
      this.storeList.map((msg)=>{
        //拿当前json的id、name、time去分别跟输入的值进行比较
        //indexOf 如果在检索的字符串中没有出现要找的值是会返回-1的，所以我们这里不等于-1就是假设输入框的值在当前json里面找到的情况
        if(msg.nickName.indexOf(this.input_value)!=-1){
          //然后把当前json添加到list数组中
          this.list.push(msg);
        }
      })
    },
    //判断用户选中的商家
    is_check(id,nickName){
      //给对应商家赋值
      this.s_id=id;
      this.s_name=nickName;
      this.input_value=nickName;
      this.state=false;
    },

    getStoreList(){
      getStore().then(response => {
        this.storeList = response.data;

      })
    },
    AddPeople() {//添加按钮
      this.list_order.push({id:this.list_order.length});
    },
    //获取from表单中添加的菜品规格和价格
    /*submitForm1(formName) {//提交按钮
      if (formName) {
        let majorAList = [];
        for (let index = 0; index < this.list_order.length; index++) {
          majorAList.push({
            postRequire: this.postRequire[index],
            comment: this.comment[index],
          });
          console.log('每一列的值', majorAList)
        }
      }
    },*/
    //删除对应菜品规格
    rev(num){
      this.list_order.splice(num,1);
      this.postRequire.splice(num,1);
      this.comment.splice(num,1);
    }
  }
};
</script>
<style>
.file {
  position: relative;
  width: 200px;
  height: 150px;
  background-color: #ccc;
}
.updata {
  display: block;
  height: 100%;
  width: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.img {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 150px;
}

</style>
